//
//  ZTXAddLineController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2023/8/25.
//  Copyright © 2023 zhuchongjin. All rights reserved.
//

#import "ZTXAddLineController.h"
#import "ZTXNewAddAdressHeaderCell.h"
#import "ZTXNewAddressCententCell.h"
#import "ZTXNewAddressBottomCell.h"
#import "MapViewController.h"
#import "MapInfoModel.h"
#import "DefaultSettingModel.h"
@interface ZTXAddLineController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) CJTableView *tableView;
@property (nonatomic, strong) NSString *typeStr;
@property (nonatomic, strong) CJButton *savaButton;
@property (nonatomic, strong) UIButton *zhAddressLabel;
@property (nonatomic, strong) UILabel *zhDitelLabel;
@property (nonatomic, strong) UIButton *xhAddressButton;
@property (nonatomic, strong) UITextView *xieDiletAddressTextView;
@property (nonatomic, strong) CJTextField *shNameTextField;
@property (nonatomic, strong) CJTextField *shPhoneTextField;
@property (nonatomic, strong) DefaultSettingModel *defaultSettingModel;
@property (nonatomic, strong) UIButton *unitButton;
@property (nonatomic, strong) NSMutableArray *unitArr;

@property (nonatomic, strong) UITextField *pressTextField;
@property (nonatomic, strong) UITextField *ciTextField;

@end

@implementation ZTXAddLineController

- (void)viewDidLoad {
    [super viewDidLoad];
    if([self.type isEqualToString:@"1"]){
        [self setTitleName:CJLString(@"修改线路")];
    }else{
        [self setTitleName:CJLString(@"新增线路")];
    }
    [self setBackLeftButton:@""];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTXNewAddAdressHeaderCell" bundle:nil] forCellReuseIdentifier:@"ZTXNewAddAdressHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTXNewAddressCententCell" bundle:nil] forCellReuseIdentifier:@"ZTXNewAddressCententCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTXNewAddressBottomCell" bundle:nil] forCellReuseIdentifier:@"ZTXNewAddressBottomCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.savaButton];
    self.unitArr = [@[] mutableCopy];
    [self btnFreightCostUnitActionType];
}
- (void)lodData{
    if([self.type isEqualToString:@"1"]){
        self.shNameTextField.text = self.consigneeName;
        self.shPhoneTextField.text = self.consigneePhone;
        [self.xhAddressButton setTitle:self.consigneeAddress forState:(UIControlStateNormal)];
        self.xieDiletAddressTextView.text = self.consigneeDetailAddress;
        self.ciTextField.text = self.ciNumberStr;
        [self.unitButton setTitle:self.conUnitName forState:(UIControlStateNormal)];
        self.pressTextField.text = self.price;
        self.typeStr = self.endType;
        if(!IsStrEmpty(self.statTimeStr)){
            self.statTimeStr = [self.statTimeStr substringToIndex:10];
        }else{
            self.statTimeStr = @"开始时间";
        }
        if(!IsStrEmpty(self.endTimeStr)){
            self.endTimeStr = [self.endTimeStr substringToIndex:10];
        }else{
            self.endTimeStr = @"结束时间";
        }
        
    }else{
        self.statTimeStr = @"开始时间";
        self.endTimeStr = @"结束时间";
        self.typeStr = @"0";
        self.ciNumberStr = @"0";
    }
}
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight -CJTableToTopHeight - CJBottomBtnHeight - SafeAreaBottomHeight - 20),UITableViewStylePlain)
            .tbDelegate(self)
            .tbDataSource(self)
            .tbSetOther(YES)
            .tbEstimatedRowHeight(YES)
            .tbMjHeadFooter(NO)
        ;
    }
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    [_tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    return _tableView;
}
- (CJButton *)savaButton{
    if (!_savaButton) {
        _savaButton = CJButton.btnInit
        .btnFrame(CGRectMake(0, self.tableView.bottom,kScreenWidth, CJBottomBtnHeight))
        .btnBgColor([UIColor cjMainColor])
        .btnText(@"保存")
        .btnNormalTitleColor([UIColor cjWhiteColor])
        .btnFontSize(17)
        .btnTargetAction(self,@selector(savaButtonAction))
        ;
    }
    return  _savaButton;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        ZTXNewAddAdressHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZTXNewAddAdressHeaderCell" forIndexPath:indexPath];
        [cell.xieAddressButton addTarget:self action:@selector(firmNamebuttonAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.zhAddressLabel = cell.zhAddressLabel;
        self.zhDitelLabel = cell.zhDiletAddressLabel;
        self.xhAddressButton = cell.xieAddressButton;
        self.xieDiletAddressTextView = cell.xieDiletAddressTextView;
        self.shNameTextField = cell.shNameTextField;
        self.shPhoneTextField = cell.shPhoneTextField;
        [self.zhAddressLabel setTitle:self.strAddressCityName forState:(UIControlStateNormal)];
        self.zhDitelLabel.text = self.shipperDetailAddress;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1){
        ZTXNewAddressCententCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZTXNewAddressCententCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.pressTextField = cell.textField;
        self.unitButton = cell.unitButton;
        if(self.unitArr > 0){
            [ self.unitButton setTitle:CJStringWithFormat(@"%@",self.conUnitName) forState:(UIControlStateNormal)];
        }
       
        [cell.unitButton addTarget:self action:@selector(unitButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    }else{
        ZTXNewAddressBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZTXNewAddressBottomCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.staterTimeButton setTitle:self.statTimeStr forState:(UIControlStateNormal)];
        [cell.endTimeButton setTitle:self.endTimeStr forState:(UIControlStateNormal)];
        self.ciTextField = cell.ciTextField;
        if([self.type isEqualToString:@"1"]){
            self.ciTextField.text = self.ciNumberStr;
        }
        cell.block = ^(id anyObject) {
            self.typeStr = anyObject;
            [self.tableView reloadSection:2 withRowAnimation:(UITableViewRowAnimationFade)];
        };
        if ([self.typeStr isEqualToString:@"0"]) {
            [cell.noOverButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
            [cell.timeOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            [cell.numberOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            cell.staterTimeButton.hidden = YES;
            cell.endTimeButton.hidden = YES;
            cell.ciTextField.hidden = YES;
        }else if ([self.typeStr isEqualToString:@"1"]) {
            [cell.noOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            [cell.timeOverButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
            [cell.numberOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            cell.staterTimeButton.hidden = NO;
            cell.endTimeButton.hidden = NO;
            cell.ciTextField.hidden = YES;
        }else{
            [cell.noOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            [cell.timeOverButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
            [cell.numberOverButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
            cell.staterTimeButton.hidden = YES;
            cell.endTimeButton.hidden = YES;
            cell.ciTextField.hidden = NO;
        }
        __block  ZTXNewAddressBottomCell *blockCell = cell;
        cell.statrTimeBlock = ^(id anyObject) {
            self.statTimeStr = anyObject;
            [blockCell.staterTimeButton setTitle:self.statTimeStr forState:(UIControlStateNormal)];
        };
        cell.endTimeBlock = ^(id anyObject) {
            self.endTimeStr = anyObject;
            [blockCell.endTimeButton setTitle:self.endTimeStr forState:(UIControlStateNormal)];
        };
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 310;
    }else if (indexPath.section == 1){
        return 60;
    }else{
        if([self.typeStr isEqualToString:@"1"]|| [self.typeStr isEqualToString:@"2"]){
            return 100;
        }else{
            return 50;
        }
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 32)];
    headerView.backgroundColor = [UIColor cjBackgroundColor];
    UILabel *linesLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 2, 20)];
    linesLabel.backgroundColor = [UIColor cjMainColor];
    UILabel *titLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(linesLabel.frame) + 15, 0, 100, 30)];
    NSArray *arr = @[@"地址信息",@"货物信息",@"结束类型"];
    titLabel.font = [UIFont systemFontOfSize:16];
    titLabel.text = arr[section];
    titLabel.textColor = [UIColor cjMainTextColor];
    UILabel *liLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titLabel.frame), SCREEN_WIDTH, 2)];
    liLabel.backgroundColor = [UIColor cjBackgroundColor];
    [headerView addSubview:linesLabel];
    [headerView addSubview:titLabel];
    [headerView addSubview:liLabel];
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section <3){
        return 32;
    }else{
        return 0.0001;
    }
}
- (void)firmNamebuttonAction{
    MapViewController *vc = [MapViewController new];
    MapInfoModel *mapInfoModel = [[MapInfoModel alloc]init];
    vc.isLocatedFirst = YES;
    vc.mapInfoModel = mapInfoModel;
    WS(ws);
    vc.blockMapInfo = ^(id anyObject) {
        MapInfoModel *model = (MapInfoModel *)anyObject;
        ws.consigneeLoadCityCode = model.adcode;
        ws.consigneeLatitude = model.latitude;
        ws.consigneeLongitude = model.longitude;
        [ws.xhAddressButton setTitle:CJStringWithFormat(@"%@%@%@",model.province,model.city,model.district) forState:(UIControlStateNormal)];
        ws.xieDiletAddressTextView.text = CJStringWithFormat(@"%@%@",[CJControl getThreeUnaryValueStr:[CJControl getThreeUnaryValueStr:model.address]],model.addressTitle);
    };
    [self pushVc:vc];
}

- (void)btnFreightCostUnitActionType{
    [self.view endEditing:NO];
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/dict/listDict",CJBaseUrl);
    NSDictionary *dicPra = @{
            @"types":CJStringWithFormat(@"goodsTransferFeeUnits0")
                            };
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
                
        NSDictionary *dic = responseObject[0];
        NSArray *array = dic[@"dictList"];
        for (NSDictionary *dict in array) {
            [ws.unitArr addObject:dict];
        }
        if( [self.type isEqualToString:@"1"]){
            if(self.unitArr > 0){
                for (NSDictionary *dic in self.unitArr) {
                    if([dic[@"code"] isEqualToString:self.conUnitCode]){
                        self.conUnitName = dic[@"name"];
                        self.conUnitCode = dic[@"code"];
                    }
                }
            }
            
        }else{
            if(self.unitArr > 0){
                NSDictionary *dic = self.unitArr.firstObject;
                self.conUnitName = dic[@"name"];
                self.conUnitCode = dic[@"code"];
                [self.unitButton setTitle:self.conUnitName forState:(UIControlStateNormal)];
            }
        }
        [self lodData];
        [self.tableView reloadRow:0 inSection:2 withRowAnimation:(UITableViewRowAnimationFade)];
    } failure:^(NSError * _Nonnull error) {
//        DLog(@"++++++++%@",error);
        
    }];

}
- (void)unitButtonAction{
    NSMutableArray *arrMutar = [[NSMutableArray array] init];
    NSMutableArray *arrMutarCodes = [[NSMutableArray array] init];
    for (NSDictionary *dic in self.unitArr) {
        [arrMutar addObject:dic[@"name"]];
        [arrMutarCodes addObject:dic[@"code"]];
    }
    [self btnSelectTypeList:arrMutar listCodes:arrMutarCodes title:@"运费计量单位"];
}
- (void)savaButtonAction{
    if(self.shNameTextField.text.length == 0){
        [CJAlert showStringDismissWithDelay:@"请输入收货人姓名"];
        return;
    }
    if(![CJRegular getcheckPhone:self.shPhoneTextField.text]){
        [CJAlert showStringDismissWithDelay:@"请输入正确的手机号"];
        return;
    }
    if(IsStrEmpty(self.consigneeLatitude)){
        [CJAlert showStringDismissWithDelay:@"请选择收获地址"];
        return;
    }
    if(self.pressTextField.text.length == 0){
        [CJAlert showStringDismissWithDelay:@"请输入运费单价"];
        return;
    }
    NSString *strURL;
    if([self.type isEqualToString:@"1"]){
        strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/update",CJBaseUrl);
    }else{
        strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/addRoutes",CJBaseUrl);
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:self.strConsigneeLatitude forKey:@"shipperLatitude"];
    [dict setValue:self.strConsigneeLongitude forKey:@"shipperLongitude"];
    [dict setValue:self.strDownLoadCityCode forKey:@"shipperSubdivisionCode"];
    [dict setValue:self.consigneeLatitude forKey:@"consigneeLatitude"];
    [dict setValue:self.consigneeLongitude forKey: @"consigneeLongitude"];
    [dict setValue:self.xieDiletAddressTextView.text forKey:@"consigneeDetailAddress"];
    [dict setValue:self.shNameTextField.text forKey:@"consigneeName"];
    [dict setValue:self.shPhoneTextField.text forKey:@"consigneePhone"];
    [dict setValue:self.pressTextField.text forKey:@"price"];
    [dict setValue:self.conUnitCode forKey:@"coalUnit"];
    [dict setValue:self.typeStr forKey:@"endType"];
    [dict setValue:self.consigneeLoadCityCode forKey:@"consigneeSubdivisionCode"];
    if([self.typeStr isEqualToString:@"1"]){
        self.statTimeStr = CJStringWithFormat(@"%@ 00:00:00",self.statTimeStr);
        self.endTimeStr = CJStringWithFormat(@"%@ 00:00:00",self.endTimeStr);
        [dict setValue:self.statTimeStr forKey:@"startTime"];
        [dict setValue:self.endTimeStr forKey:@"endTime"];
    }else if ([self.typeStr isEqualToString:@"2"]){
        [dict setValue:self.ciTextField.text forKey:@"remainTime"];
    }
    if([self.type isEqualToString:@"1"]){
        [dict setValue:self.code forKey:@"code"];
    }
    [dict setValue:self.projectCode forKey:@"projectCode"];
    [dict setValue:self.conUnitCode forKey:@"isTrunk"];
    [dict setValue:self.coalBigTypeName forKey:@"coalBigTypeName"];
    [dict setValue:self.coalBigType forKey:@"coalBigType"];
    [dict setValue:self.coalType forKey:@"coalType"];
    [dict setValue:self.coalTypeName forKey:@"coalTypeName"];
    [dict setValue:self.shipperDetailAddress forKey:@"shipperDetailAddress"];

    WS(ws);
    if([self.type isEqualToString:@"1"]){
        [[HDNetworking sharedHDNetworking] jsonTaskWithHTTPMethod:PutType urlString:strURL withParameter:dict status:OperationTip success:^(id  _Nonnull responseObject) {
            NSLog(@"%@",responseObject);
            [ws pop];
        } failure:^(NSError * _Nonnull error) {

        }];
    }else{
        [[HDNetworking sharedHDNetworking] jsonTaskWithHTTPMethod:PostType urlString:strURL withParameter:dict status:OperationTip success:^(id  _Nonnull responseObject) {
            NSLog(@"%@",responseObject);
            [ws pop];
        } failure:^(NSError * _Nonnull error) {

        }];
    }

}
- (void)btnSelectTypeList:(NSArray *)list listCodes:(NSMutableArray *)arryCodes title:(NSString *)strTitle{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = list;
    WS(ws);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        NSDictionary *dic = self.unitArr[resultModel.index];
        ws.conUnitName = dic[@"name"];
        ws.conUnitCode = dic[@"code"];
        [self.unitButton setTitle:ws.conUnitName forState:(UIControlStateNormal)];
    };
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}
@end
